var crypto = require('crypto');
var request = require('request');
var config = require('./config');
var util = require('util');
var async = require('async');
var fs = require('fs');
var logger = require('./logger');
var nodemailer = require('nodemailer');
var smtpTransport = require('nodemailer-smtp-transport');
var exec = require('child_process').exec;
var path = require('path');

exports.isArray = util.isArray;
exports.format = util.format;

exports.md5 = function (key) {
    var hash = crypto.createHash('md5');
    hash.update(key);
    return hash.digest('hex');
};

exports.base64Encode = function (str) {
    return new Buffer(str.toString()).toString("base64");
};

exports.base64Decode = function (str) {
    return new Buffer(str,'base64').toString("ascii");
};

exports.isQQ = function (id) {
    return /^[1-9]\d{4,12}$/.test(id);
};

exports.isTel = function (id) {
    return /^1[3-8][0-9]{9}$/.test(id) || /^\d{3,4}-\d{7,8}$/.test(id);
};

exports.isImageUrl = function (id) {
    return /^(http(s)?:\\)?\w+?\.(png|jpg|gif|bmp)$/.test(id);
};

exports.isEmail = function (id) {
    return /^[0-9a-zA-Z_+-\.]+@.{1,20}\..{1,10}$/.test(id);
};

exports.isValidId = function (id) {
    if (!id)
        return false;
    else
        return /^[0-9a-fA-F]{24}$/.test(id);
};

exports.get = function (url, cb) {
    //var time = Date.now();
    request({url: url}, function (err, resp, body) {
        //logger.info('get :%s cost:',url,Date.now() - time);
        cb(err, body);
    });
};

exports.longPost = function (url, data, cb) {
    var time = Date.now();
    request.post({
        headers: {'content-type': 'application/x-www-form-urlencoded'},
        url: url,
        body: data
    }, function (err, resp, body) {
        logger.info('get :%s cost:',url,Date.now() - time);
        cb(err, body);
    });
};

exports.post = function (url, data, cb) {
    request.post({
        headers: {'content-type': 'application/x-www-form-urlencoded'},
        url: url,
        body: data,
        jar:true,
        timeout: config.respTimeout
    }, function (err, resp, body) {
        cb(err, body);
    });
};

exports.postJson = function (url, data, cb) {
    request.post({
        headers: {'content-type': 'application/json'},
        url: url,
        body: data,
        jar:true,
        timeout: config.respTimeout
    }, function (err, resp, body) {
        cb(err, body);
    });
};

exports.download = function (url,local,cb) {
    var stream = fs.createWriteStream(local);
    stream.on('close',cb);
    request(url).pipe(stream);
};

exports.addressSplit = function (address) {
    var result = {};
    var province, city, area;
    var cityArr = ["北京", "天津", "上海", "重庆"];
    var areaArr = ["市", "县", "区", "旗", "镇"];

    var isDirect = false;
    province = address.indexOf("省", 0);
    if(province == -1){
        for (var i in cityArr) {
            province = address.indexOf(cityArr[i], 0);
            if (province != -1) {
                isDirect = true;
                result.province = address.substr(0,cityArr[i].length);
                break;
            }
        }
    }else{
        result.province = address.substr(0, province);
    }

    if(isDirect){
        result.city = result.province;
    }else{
        city = address.indexOf("市", province + 1);
        if (city != -1)
            result.city = address.substr(province + 1,city - province);
        else
            return result;
    }

    for (var i in areaArr) {
        area = address.indexOf(areaArr[i], city + 1);
        if (area != -1) {
            result.district = address.substr(city+1, area - city);
            break;
        }
    }

    return result;
};

exports.getDateTimeString = function (date) {
    var d = date;
    if(!util.isDate(date))
        d = new Date();

    var month = d.getMonth() + 1;
    var day = d.getDate();
    if(month < 10){
        month = '0' + month;
    }

    if(day < 10){
        day = '0' + day;
    }

    return d.getFullYear() + '-' + month + '-' + day + ' ' + d.toLocaleTimeString();
};

exports.getLocalDateTimeString = function (date) {
    var d = date;
    if(!util.isDate(date))
        d = new Date();

    var month = d.getMonth() + 1;
    d.setHours(d.getHours()+8);
    return d.getFullYear() + '-' + month + '-' + d.getDate() + ' ' + d.toLocaleTimeString();
};

exports.getDateString = function (date) {
    var d = date;
    if(!util.isDate(date))
        d = new Date();

    var month = d.getMonth() + 1;
    var day = d.getDate();
    if(month < 10){
        month = '0' + month;
    }

    if(day < 10){
        day = '0' + day;
    }

    return d.getFullYear() + '-' + month + '-' + day;
};

exports.formatDate = function (docs) {
    if(util.isArray(docs)){
        for(var i in docs){
            if(docs[i].date){
                var date = docs[i].date;
                docs[i].date = this.getDateTimeString(date);
            }
        }
    }
};

exports.send = function(mobile,msg,cb){
    var url = config.msgHost + '&uid=' + config.msgUid + '&auth=' + config.msgPassword + '&mobile=' + mobile + '&msg=' + encodeURIComponent(msg);
    logger.info('send msg:',url);
    request({url:url}, function (err,resp,body) {
        if(err){
            cb(err,null);
        }else{
            var result = body.split(',');
            var code = parseInt(result[0]);
            cb(null,code);
        }
    });
};

exports.sendMail = function(address,content,attachments,cb){
    var transporter = nodemailer.createTransport(smtpTransport({
        host: config.monitorMail.smtp,
        port:25,
        auth: {
            user: config.monitorMail.username,
            pass: config.monitorMail.password
        }
    }));

    var mailOptions = {
        from:config.monitorMail.username,
        to:address,
        subject: config.monitorMail.subject,
        html:content
    };

    if(attachments){
        mailOptions.attachments = attachments;
    }

    transporter.sendMail(mailOptions,cb);
};

exports.sendBrokenMail = function(address,content,attachments,cb){
    var transporter = nodemailer.createTransport(smtpTransport({
        host: config.monitorMail.smtp,
        port:25,
        auth: {
            user: config.monitorMail.username,
            pass: config.monitorMail.password
        }
    }));

    var mailOptions = {
        from:config.monitorMail.username,
        to:address,
        subject: config.monitorMail.subject,
        html:content
    };

    if(attachments){
        mailOptions.attachments = attachments;
    }

    transporter.sendMail(mailOptions,cb);
};

exports.sendNotifyMail = function(address,title,content,cb){
    var transporter = nodemailer.createTransport(smtpTransport({
        host: config.monitorMail.smtp,
        port:25,
        auth: {
            user: config.monitorMail.username,
            pass: config.monitorMail.password
        }
    }));

    var mailOptions = {
        from:config.monitorMail.username,
        to:address,
        subject: title,
        html:content
    };
    transporter.sendMail(mailOptions,cb);
};

exports.getDate = function(start,end){
    if(!end){
        end = start;
    }
    var start = new Date(start);
    start.setHours(0);
    start.setMinutes(0);
    start.setSeconds(0);
    var end = new Date(end);
    end.setHours(23);
    end.setMinutes(59);
    end.setSeconds(59);
    var date = {};
    date.start = start;
    date.end = end;
    return date;
};

exports.local2remote = function(url,host){
    return host + path.normalize(url.replace(/^uploads/,''));
};
